import React, { useState, useEffect, useMemo } from 'react';
import { Card, Button, Row, Col, Typography, Form, Input, message, Popconfirm, Slider, Modal, Tabs, Tag, Menu, Select } from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  FundOutlined,
  FileSearchOutlined,
  BarChartOutlined,
  HomeOutlined,
  RightOutlined
} from '@ant-design/icons';
import { Strategy, type AssetAllocation, RiskLevel } from '../types/strategies';
import { strategyApi } from '../lib/api';
import MarketingStrategyLibrary from '../components/MarketingStrategyLibrary';
import AnalyzeBasePage from '../components/AnalyzeBasePage';
import ResearchReportPage from '../components/ResearchReportPage';
import BusinessGuidancePage from '../components/BusinessGuidancePage';
import { type StrategyFormData } from '../types/strategies';

const { Title, Text } = Typography;

// 资产配置滑块组件
const AllocationSliders: React.FC<{
  allocation: AssetAllocation;
  editable?: boolean;
  onChange?: (newAllocation: AssetAllocation) => void;
  isGlobalStrategy?: boolean; // 是否为全球配置策略
}> = ({ allocation, editable = false, onChange, isGlobalStrategy = false }) => {
  const [localAllocation, setLocalAllocation] = useState(allocation);

  useEffect(() => {
    setLocalAllocation(allocation);
  }, [allocation]);

  const handleSliderChange = (key: keyof AssetAllocation, value: [number, number]) => {
    const newAllocation = { ...localAllocation, [key]: value };
    setLocalAllocation(newAllocation);
    if (onChange) {
      onChange(newAllocation);
    }
  };

  const sliderConfig = [
    { key: 'currency' as keyof AssetAllocation, label: '货币类', color: '#1677ff' },
    { key: 'fixedIncome' as keyof AssetAllocation, label: '固收类', color: '#52c41a' },
    { key: 'equity' as keyof AssetAllocation, label: '权益类', color: '#fa8c16' },
    { key: 'alternative' as keyof AssetAllocation, label: '另类', color: '#722ed1' },
  ];

  // 如果是全球配置策略，添加QDII滑块
  const globalSliderConfig = [
    ...sliderConfig,
    { key: 'qdii' as keyof AssetAllocation, label: 'QDII', color: '#13c2c2' },
  ];

  return (
      <div className="allocation-sliders">
        {(isGlobalStrategy ? globalSliderConfig : sliderConfig).map((config) => {
          const allocationValue = localAllocation[config.key];
          if (!allocationValue || !Array.isArray(allocationValue)) return null;
          const [min, max] = allocationValue;
          return (
              <div key={config.key} className="mb-4">
                <div className="flex justify-between items-center mb-2">
              <span className="text-sm font-medium" style={{ color: config.color }}>
                {config.label}
              </span>
                  <span className="text-xs text-gray-500">
                {min}% - {max}%
              </span>
                </div>
                <Slider
                    range
                    min={0}
                    max={100}
                    value={[min, max]}
                    onChange={(value) => handleSliderChange(config.key, value as [number, number])}
                    disabled={!editable}
                    styles={{
                      track: { backgroundColor: config.color },
                      handle: { borderColor: config.color }
                    }}
                    tooltip={{
                      formatter: (value) => `${value}%`
                    }}
                />
              </div>
          );
        })}
      </div>
  );
};

// 策略类型常量
const STRATEGY_TYPES = {
  RISK: '风险性策略',
  LIQUIDITY: '流动性策略',
  GLOBAL: '全球配置策略'
} as const;

const CustomStrategyForm: React.FC<{
  strategy?: Strategy;
  onSave: (data: StrategyFormData) => void;
  onCancel: () => void;
}> = ({ strategy, onSave, onCancel }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [allocation, setAllocation] = useState<AssetAllocation>({
    currency: [0, 10],
    fixedIncome: [40, 60],
    equity: [20, 40],
    alternative: [0, 10],
    qdii: [5, 10]
  });

  // 策略分类选项
  const categoryOptions = [
    { value: STRATEGY_TYPES.RISK, label: '风险性策略' },
    { value: STRATEGY_TYPES.LIQUIDITY, label: '流动性策略' },
    { value: STRATEGY_TYPES.GLOBAL, label: '全球配置策略' },
    { value: '自定义策略', label: '自定义策略' }
  ];

  // 风险等级选项
  const riskLevelOptions = [
    { value: RiskLevel.R1, label: 'R1' },
    { value: RiskLevel.R2, label: 'R2' },
    { value: RiskLevel.R3, label: 'R3' },
    { value: RiskLevel.R4, label: 'R4' },
    { value: RiskLevel.R5, label: 'R5' }
  ];

  // 流动性选项
  const liquidityOptions = [
    { value: '高流动性', label: '高流动性' },
    { value: '中/低流动性', label: '中/低流动性' }
  ];

  useEffect(() => {
    if (strategy) {
      form.setFieldsValue({
        name: strategy.strategy_name,
        description: strategy.strategy_detail.description,
        category: strategy.strategy_category,
        riskLevel: strategy.strategy_detail.riskLevel,
        liquidity: strategy.strategy_detail.liquidity
      });
      setAllocation(strategy.strategy_detail.coreAllocation);
    }
  }, [strategy, form]);

  const handleSubmit = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();

      const strategyData: StrategyFormData = {
        name: values.name.trim(),
        description: values.description.trim(),
        category: values.category,
        riskLevel: values.riskLevel,
        liquidity: values.liquidity,
        coreAllocation: allocation,
        created_by: 'current_user',
        updated_by: 'current_user'
      };

      await onSave(strategyData);
      form.resetFields();
      form.setFieldsValue({
        name: '',
        description: '',
        category: '自定义策略',
        riskLevel: RiskLevel.R3,
        liquidity: '高流动性'
      });
      setAllocation({
        currency: [0, 10],
        fixedIncome: [40, 60],
        equity: [20, 40],
        alternative: [0, 10],
        qdii: [5, 10]
      });
    } catch (error) {
      console.error('Form validation failed:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
      <Card>
        <Form
            form={form}
            layout="vertical"
            initialValues={{
              name: '',
              description: '',
              category: '自定义策略',
              riskLevel: RiskLevel.R3,
              liquidity: '高流动性'
            }}
        >
          <Form.Item
              name="name"
              label="策略名称"
              rules={[{ required: true, message: '请输入策略名称' }]}
          >
            <Input placeholder="请输入策略名称" />
          </Form.Item>

          <Form.Item
              name="category"
              label="策略分类"
              rules={[{ required: true, message: '请选择策略分类' }]}
          >
            <Select placeholder="请选择策略分类">
              {categoryOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
              name="riskLevel"
              label="风险等级"
          >
            <Select placeholder="请选择风险等级">
              {riskLevelOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
              name="liquidity"
              label="流动性"
          >
            <Select placeholder="请选择流动性">
              {liquidityOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
              name="description"
              label="策略描述"
              rules={[{ required: true, message: '请输入策略描述' }]}
          >
            <Input.TextArea
                placeholder="请输入策略描述"
                rows={4}
            />
          </Form.Item>

          <div className="mb-4">
            <Text strong>资产配置范围</Text>
            <div className="mt-3 p-4 bg-gray-50 rounded">
              <AllocationSliders
                  allocation={allocation}
                  editable={true}
                  onChange={setAllocation}
                  isGlobalStrategy={strategy?.strategy_category === STRATEGY_TYPES.GLOBAL}
              />
            </div>
          </div>

          <div className="flex gap-3 justify-end">
            <Button onClick={onCancel}>
              取消
            </Button>
            <Button type="primary" onClick={handleSubmit} loading={loading}>
              {strategy ? '更新策略' : '创建策略'}
            </Button>
          </div>
        </Form>
      </Card>
  );
};

// GeneralStrategyLibrary 资产配置策略区，合并自定义策略卡片
const GeneralStrategyLibrary: React.FC<{
  onDiagnose: (strategy: Strategy) => void;
  strategies: Strategy[];
  customStrategies: Strategy[];
  loading: boolean;
  onRefresh: () => void;
  showHeader?: boolean;
}> = ({ strategies, customStrategies, loading, onRefresh }) => {
  const [selectedCategory, setSelectedCategory] = useState<string>('所有策略');
  const [editingStrategy, setEditingStrategy] = useState<Strategy | null>(null);
  const [modalOpen, setModalOpen] = useState(false);

  // 合并所有策略
  const allStrategies = useMemo(() => {
    return [...strategies, ...customStrategies];
  }, [strategies, customStrategies]);

  // 策略分类定义
  const strategyCategories = useMemo(() => {
    const categories = ['所有策略', STRATEGY_TYPES.RISK, STRATEGY_TYPES.LIQUIDITY, STRATEGY_TYPES.GLOBAL];
    if (customStrategies.length > 0) {
      categories.push('自定义策略');
    }
    return categories;
  }, [customStrategies]);

  // 根据分类过滤策略
  const filteredStrategies = useMemo(() => {
    if (selectedCategory === '所有策略') return allStrategies;
    if (selectedCategory === '自定义策略') return customStrategies;
    return strategies.filter(s => s.strategy_category === selectedCategory);
  }, [selectedCategory, allStrategies, strategies, customStrategies]);

  // 获取分类统计
  const getCategoryCount = (category: string) => {
    if (category === '所有策略') return allStrategies.length;
    if (category === '自定义策略') return customStrategies.length;
    return strategies.filter(s => s.strategy_category === category).length;
  };

  // 策略卡片组件
  const StrategyCard: React.FC<{
    strategy: Strategy;
    showActions?: boolean;
  }> = ({ strategy, showActions = true }) => (
      <Card
          className="strategy-card hover:shadow-lg transition-all duration-300"
          size="small"
          style={{
            borderRadius: '12px',
            background: 'linear-gradient(135deg, #ffffff 0%, #fafafa 100%)',
            border: '1px solid #f0f0f0',
            minHeight: 320
          }}
          actions={showActions ? [
            <Button type="text" className="text-blue-500 hover:text-blue-700" icon={<EditOutlined />} onClick={() => { setEditingStrategy(strategy); setModalOpen(true); }}>编辑</Button>,
            <Popconfirm title="确定删除该策略？" onConfirm={() => handleDelete(strategy)} okText="确定" cancelText="取消">
              <Button type="text" icon={<DeleteOutlined />} danger>删除</Button>
            </Popconfirm>
          ] : undefined}
      >
        <div className="space-y-3">
          <div className="flex items-center gap-2 mb-3">
            <Title level={5} className="!mb-0">{strategy.strategy_name}</Title>
          </div>
          
          {/* 策略标签 */}
          <div className="flex flex-wrap gap-1 mb-3">
            {strategy.strategy_detail.riskLevel && (
              <Tag color="orange" className="mb-1">
                {strategy.strategy_detail.riskLevel}
              </Tag>
            )}
            {strategy.strategy_detail.liquidity && (
              <Tag color="green" className="mb-1">
                {strategy.strategy_detail.liquidity}
              </Tag>
            )}
          </div>

          <Text type="secondary" className="text-sm block mb-3">{strategy.strategy_detail.description}</Text>
          
          <div className="bg-gray-50 p-3 rounded">
            <Text strong className="block mb-2">核心配置</Text>
            <AllocationSliders
                allocation={strategy.strategy_detail.coreAllocation}
                editable={false}
                isGlobalStrategy={strategy.strategy_category === STRATEGY_TYPES.GLOBAL}
            />
          </div>
        </div>
      </Card>
  );

  const handleSave = async (data: StrategyFormData) => {
    try {
      let response;
      if (editingStrategy) {
        // 编辑现有策略
        const strategyId = typeof editingStrategy.id === 'string' ? parseInt(editingStrategy.id) : editingStrategy.id;
        response = await strategyApi.updateStrategy(strategyId, {
          strategy_name: data.name,
          strategy_category: data.category,
          strategy_detail: {
            description: data.description,
            coreAllocation: data.coreAllocation,
            riskLevel: data.riskLevel,
            liquidity: data.liquidity
          },
          updated_by: data.updated_by
        });
      } else {
        // 创建新策略
        response = await strategyApi.createStrategy({
          strategy_name: data.name,
          strategy_category: data.category,
          strategy_detail: {
            description: data.description,
            coreAllocation: data.coreAllocation,
            riskLevel: data.riskLevel,
            liquidity: data.liquidity
          },
          created_by: data.created_by,
          updated_by: data.updated_by
        });
      }

      if (response.success) {
        message.success(editingStrategy ? '策略更新成功' : '策略创建成功');
        setEditingStrategy(null);
        setModalOpen(false);
        onRefresh();
      } else {
        message.error(response.error || (editingStrategy ? '策略更新失败' : '策略创建失败'));
      }
    } catch (error) {
      console.error('保存策略时出错:', error);
      message.error('操作失败，请重试');
    }
  };

  const handleDelete = async (strategy: Strategy) => {
    try {
      const strategyId = typeof strategy.id === 'string' ? parseInt(strategy.id) : strategy.id;
      const response = await strategyApi.deleteStrategy(strategyId);
      if (response.success) {
        message.success('策略删除成功');
        onRefresh();
      } else {
        message.error(response.error || '策略删除失败');
      }
    } catch (error) {
      console.error('删除策略时出错:', error);
      message.error('删除失败，请重试');
    }
  };

  return (
      <div className="strategy-library-container flex" style={{ height: '100%' }}>
        {/* 左侧分类菜单 */}
        <div className="w-64 bg-gray-50 border-r border-gray-200 p-4">
          <div className="mb-6">
            <Title level={4} className="!mb-4 text-gray-800">策略分类</Title>
          </div>
          <Menu
            mode="inline"
            selectedKeys={[selectedCategory]}
            className="bg-transparent border-none"
            items={strategyCategories.map(category => ({
              key: category,
              label: (
                <div className="flex justify-between items-center">
                  <span>{category}</span>
                  <Tag color="blue" className="ml-2">
                    {getCategoryCount(category)}
                  </Tag>
                </div>
              ),
              onClick: () => setSelectedCategory(category)
            }))}
          />
        </div>

        {/* 右侧内容区 */}
        <div className="flex-1 flex flex-col">
          {/* 顶部操作区 */}
          <div className="mb-3 flex justify-between items-center px-6 py-4 bg-white border-b border-gray-200">
            <div>
              <Title level={3} className="!mb-2">{selectedCategory}</Title>
              <Text type="secondary" className="text-sm">
                共有 <span className="font-semibold text-blue-600">{filteredStrategies.length}</span> 个策略
              </Text>
            </div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setModalOpen(true)}
              className="shadow-sm"
              style={{ borderRadius: 8, height: 40 }}
            >
              新建策略
            </Button>
          </div>

          {/* 卡片列表滚动区 */}
          <div className="flex-1 px-6" style={{ overflowY: 'auto' }}>
            {loading ? (
              <div className="text-center py-12">
                <div className="animate-spin w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full mx-auto mb-4"></div>
                <Text className="text-gray-600">正在加载策略...</Text>
              </div>
            ) : filteredStrategies.length === 0 ? (
              <div className="text-center py-12">
                <FundOutlined className="text-4xl text-gray-400 mb-4" />
                <Title level={4} className="!mb-2 text-gray-500">暂无策略</Title>
                <Text type="secondary">
                  {selectedCategory === '所有策略' 
                    ? '点击"新建策略"按钮开始创建您的第一个策略'
                    : `当前分类"${selectedCategory}"下暂无策略`
                  }
                </Text>
              </div>
            ) : (
              <Row gutter={[16, 16]}>
                {filteredStrategies.map((strategy) => (
                  <Col xs={24} sm={12} md={8} lg={8} xl={8} key={strategy.id}>
                    <StrategyCard strategy={strategy} />
                  </Col>
                ))}
              </Row>
            )}
          </div>
        </div>

        {/* 新建/编辑弹窗 */}
        <Modal
            title={editingStrategy ? '编辑资产配置策略' : '新建资产配置策略'}
            open={modalOpen}
            onCancel={() => { setEditingStrategy(null); setModalOpen(false); }}
            footer={null}
            destroyOnHidden
        >
          <CustomStrategyForm
              strategy={editingStrategy || undefined}
              onSave={handleSave}
              onCancel={() => { setEditingStrategy(null); setModalOpen(false); }}
          />
        </Modal>
      </div>
  );
};

// StrategyLibrary 只保留资产配置策略tab，合并自定义策略
const StrategyLibrary: React.FC<{ onDiagnose: (strategy: Strategy) => void }> = ({ onDiagnose }) => {
  const [allStrategies, setAllStrategies] = useState<Strategy[]>([]);
  const [customStrategies, setCustomStrategies] = useState<Strategy[]>([]);
  const [loading, setLoading] = useState(false);

  // 获取所有策略数据
  const fetchAllStrategies = async () => {
    setLoading(true);
    try {
      const res = await strategyApi.getStrategies();
      if (res.success && res.data) {
        if (Array.isArray(res.data.strategies)) {
          const strategies = res.data.strategies;
          setAllStrategies(strategies.filter((s: Strategy) => s.strategy_category !== '自定义策略'));
          setCustomStrategies(strategies.filter((s: Strategy) => s.strategy_category === '自定义策略'));
        } else {
          message.error('策略数据格式不正确');
        }
      } else {
        message.error(res.error || '获取策略列表失败');
      }
    } catch (error) {
      message.error('获取策略列表出错');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAllStrategies();
  }, []);

  const refreshStrategies = () => {
    fetchAllStrategies();
  };

  return (
      <GeneralStrategyLibrary
          onDiagnose={onDiagnose}
          strategies={allStrategies}
          customStrategies={customStrategies}
          loading={loading}
          onRefresh={refreshStrategies}
          showHeader={true}
      />
  );
};

// 经营引导策略组件（占位符）
const BusinessGuidanceStrategy: React.FC = () => {
  return (
      <div className="h-full">
        <BusinessGuidancePage />
      </div>
  );
};

// 策略库内容页面（包含子tab切换）
const StrategyContent: React.FC<{ onBack: () => void }> = ({ onBack }) => {
  const [activeTab, setActiveTab] = useState<string>('asset');

  const tabItems = [
    {
      key: 'asset',
      label: '资产配置策略',
      children: <StrategyLibrary onDiagnose={() => {}} />
    },
    {
      key: 'marketing',
      label: '营销策略',
      children: <MarketingStrategyLibrary />
    },
    {
      key: 'business',
      label: '经营引导策略',
      children: <BusinessGuidanceStrategy />
    }
  ];

  return (
      <div style={{ 
        height: '100vh', 
        display: 'flex', 
        flexDirection: 'column',
        overflow: 'hidden'
      }}>
        {/* 面包屑导航 - 固定不滚动 */}
        <div className="mb-6" style={{
          display: 'flex',
          alignItems: 'center',
          fontSize: '16px',
          background: '#f8f9fa',
          padding: '12px 16px',
          borderRadius: '8px',
          border: '1px solid #e9ecef',
          flexShrink: 0
        }}>
          <div style={{
            background: '#1890ff',
            borderRadius: '50%',
            width: '24px',
            height: '24px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginRight: '12px'
          }}>
            <HomeOutlined style={{ color: '#fff', fontSize: '12px' }} />
          </div>
          <span
              onClick={onBack}
              style={{
                cursor: 'pointer',
                color: '#666',
                fontSize: '14px'
              }}
              className="hover:text-blue-500 transition-colors"
          >
          常用工具库
        </span>
          <RightOutlined style={{
            color: '#ccc',
            fontSize: '10px',
            margin: '0 8px'
          }} />
          <span style={{
            color: '#1890ff',
            fontSize: '14px',
            fontWeight: 500
          }}>
          策略库
        </span>
        </div>

        {/* Tab切换 - 内容区域可滚动 */}
        <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          <Tabs
              activeKey={activeTab}
              onChange={setActiveTab}
              items={tabItems.map(item => ({
                ...item,
                children: (
                  <div style={{ 
                    height: 'calc(100vh - 143px)', 
                    overflowY: 'auto'
                  }}>
                    {item.children}
                  </div>
                )
              }))}
              size="large"
              style={{ height: '100%' }}
              tabBarStyle={{
                marginBottom: 16,
                borderBottom: '2px solid #f0f0f0',
                flexShrink: 0
              }}
          />
        </div>
      </div>
  );
};

// 专家框架管理内容页面
const AnalyzeContent: React.FC<{ onBack: () => void }> = ({ onBack }) => {
  return (
      <div style={{ 
        height: '100vh', 
        display: 'flex', 
        flexDirection: 'column',
        overflow: 'hidden'
      }}>
        {/* 面包屑导航 - 固定不滚动 */}
        <div className="mb-6" style={{
          display: 'flex',
          alignItems: 'center',
          fontSize: '16px',
          background: '#f8f9fa',
          padding: '12px 16px',
          borderRadius: '8px',
          border: '1px solid #e9ecef',
          flexShrink: 0
        }}>
          <div style={{
            background: '#1890ff',
            borderRadius: '50%',
            width: '24px',
            height: '24px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginRight: '12px'
          }}>
            <HomeOutlined style={{ color: '#fff', fontSize: '12px' }} />
          </div>
          <span
              onClick={onBack}
              style={{
                cursor: 'pointer',
                color: '#666',
                fontSize: '14px'
              }}
              className="hover:text-blue-500 transition-colors"
          >
          常用工具库
        </span>
          <RightOutlined style={{
            color: '#ccc',
            fontSize: '10px',
            margin: '0 8px'
          }} />
          <span style={{
            color: '#1890ff',
            fontSize: '14px',
            fontWeight: 500
          }}>
          专家框架管理
        </span>
        </div>
        
        {/* 内容区域 - 可滚动 */}
        <div style={{ 
          flex: 1, 
          overflowY: 'auto'
        }}>
          <AnalyzeBasePage />
        </div>
      </div>
  );
};

// 研报解读内容页面
const ResearchReportContent: React.FC<{ onBack: () => void }> = ({ onBack }) => {
  return (
      <div style={{ 
        height: '100vh', 
        display: 'flex', 
        flexDirection: 'column',
        overflow: 'hidden'
      }}>
        {/* 面包屑导航 - 固定不滚动 */}
        <div className="mb-6" style={{
          display: 'flex',
          alignItems: 'center',
          fontSize: '16px',
          background: '#f8f9fa',
          padding: '12px 16px',
          borderRadius: '8px',
          border: '1px solid #e9ecef',
          flexShrink: 0
        }}>
          <div style={{
            background: '#1890ff',
            borderRadius: '50%',
            width: '24px',
            height: '24px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginRight: '12px'
          }}>
            <HomeOutlined style={{ color: '#fff', fontSize: '12px' }} />
          </div>
          <span
              onClick={onBack}
              style={{
                cursor: 'pointer',
                color: '#666',
                fontSize: '14px'
              }}
              className="hover:text-blue-500 transition-colors"
          >
          常用工具库
        </span>
          <RightOutlined style={{
            color: '#ccc',
            fontSize: '10px',
            margin: '0 8px'
          }} />
          <span style={{
            color: '#1890ff',
            fontSize: '14px',
            fontWeight: 500
          }}>
          研报解读
        </span>
        </div>
        
        {/* 内容区域 - 可滚动 */}
        <div style={{ 
          flex: 1, 
          overflowY: 'auto'
        }}>
          <ResearchReportPage />
        </div>
      </div>
  );
};

// 主页面卡片组件
const ToolsCards: React.FC<{ onCardClick: (type: 'strategy' | 'analyze' | 'research_report') => void }> = ({ onCardClick }) => {
  const cards = [
    {
      key: 'strategy' as const,
      title: '策略库',
      description: '智能投资策略管理平台，提供专业的资产配置建议和营销策略支持，助力投资决策优化。',
      icon: <FundOutlined style={{ fontSize: '32px', color: '#6366f1' }} />,
      gradient: 'linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%)',
      status: '策略已激活',
      bgPattern: 'rgba(255, 255, 255, 0.1)'
    },
    {
      key: 'analyze' as const,
      title: '专家框架管理',
      description: '专业的分析框架和智能工具集，提供深度市场洞察和数据驱动的投资分析解决方案。',
      icon: <BarChartOutlined style={{ fontSize: '32px', color: '#f59e0b' }} />,
      gradient: 'linear-gradient(135deg, #f97316 0%, #ea580c 100%)',
      status: '框架运行中',
      bgPattern: 'rgba(255, 255, 255, 0.1)'
    },
    {
      key: 'research_report' as const,
      title: '研报解读',
      description: 'AI驱动的研究报告智能解读平台，快速提取关键信息，提供准确的投资研究支持。',
      icon: <FileSearchOutlined style={{ fontSize: '32px', color: '#06b6d4' }} />,
      gradient: 'linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%)',
      status: '解读服务在线',
      bgPattern: 'rgba(255, 255, 255, 0.1)'
    }/*,
    {
      key: 'agents' as const,
      title: 'Agent编排',
      description: '设计、协调和管理多个独立的、具有特定能力的 AI 智能体（Agents）协同工作。',
      icon: <ApartmentOutlined style={{ fontSize: '32px', color: '#06b6d4' }} />,
      gradient: 'linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%)',
      status: 'Agent在线编排',
      bgPattern: 'rgba(255, 255, 255, 0.1)'
    }*/
  ];

  return (
      <div className="min-h-screen flex flex-col items-center justify-center" style={{ padding: '40px 20px' }}>
        <Row gutter={[32, 32]} justify="center" style={{ maxWidth: '1200px', width: '100%' }}>
          {cards.map((card) => (
              <Col xs={24} sm={24} md={6} key={card.key}>
                <Card
                    hoverable
                    className="tool-card cursor-pointer transition-all duration-300 hover:shadow-2xl hover:scale-105"
                    style={{
                      height: '400px',
                      borderRadius: '24px',
                      border: 'none',
                      background: card.gradient,
                      overflow: 'hidden',
                      position: 'relative'
                    }}
                    styles={{ body: {
                      padding: '32px 24px',
                      height: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'space-between',
                      position: 'relative',
                      zIndex: 2
                    }}}
                    onClick={() => onCardClick(card.key)}
                >
                  {/* 背景装饰图案 */}
                  <div
                      style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        background: card.bgPattern,
                        backgroundImage: `radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.2) 0%, transparent 50%), 
                                   radial-gradient(circle at 80% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%)`,
                        zIndex: 1
                      }}
                  />

                  {/* 主要内容区域 */}
                  <div
                      style={{
                        background: 'rgba(255, 255, 255, 0.95)',
                        borderRadius: '16px',
                        padding: '24px 20px',
                        margin: '0 -8px',
                        backdropFilter: 'blur(10px)',
                        border: '1px solid rgba(255, 255, 255, 0.2)',
                        boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)'
                      }}
                  >
                    <div className="text-center mb-4">
                      {card.icon}
                    </div>
                    <Title level={4} className="!mb-3 text-center text-gray-800">{card.title}</Title>
                    <Text
                        type="secondary"
                        className="block text-center text-sm leading-relaxed"
                        style={{
                          fontSize: '13px',
                          lineHeight: '1.5',
                          color: '#64748b'
                        }}
                    >
                      {card.description}
                    </Text>
                  </div>

                  {/* 底部状态指示器 */}
                  <div
                      style={{
                        background: '#1890ff',
                        borderRadius: '20px',
                        padding: '8px 16px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        marginTop: '16px',
                        backdropFilter: 'blur(10px)',
                        boxShadow: '0 4px 12px rgba(24, 144, 255, 0.3)'
                      }}
                  >
                    <Text style={{ color: '#fff', fontSize: '12px', fontWeight: 500 }}>
                      {card.status}
                    </Text>
                  </div>
                </Card>
              </Col>
          ))}
        </Row>
      </div>
  );
};

const ToolsLibraryPage: React.FC = () => {
  const [currentView, setCurrentView] = useState<'cards' | 'strategy' | 'analyze' | 'research_report'>('cards');

  const handleCardClick = (type: 'strategy' | 'analyze' | 'research_report') => {
    setCurrentView(type);
  };

  const handleBack = () => {
    setCurrentView('cards');
  };

  return (
      <div style={{ paddingLeft: 32, paddingRight: 24}}>
        {currentView === 'cards' && <ToolsCards onCardClick={handleCardClick} />}
        {currentView === 'strategy' && <StrategyContent onBack={handleBack} />}
        {currentView === 'analyze' && <AnalyzeContent onBack={handleBack} />}
        {currentView === 'research_report' && <ResearchReportContent onBack={handleBack} />}
        {/*currentView === 'agents' && <AgentsContent onBack={handleBack} />*/}
      </div>
  );
};

export default ToolsLibraryPage;
